import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getUser, isLoggedIn, logout as authLogout } from '@/utils/auth.js'

/**
 * 用户状态管理store
 */
export const useUserStore = defineStore('user', () => {
  // 用户信息
  const user = ref(null)

  // 初始化用户信息
  const initUser = () => {
    if (isLoggedIn()) {
      const userData = getUser()
      if (userData) {
        user.value = userData
      }
    }
  }

  // 计算属性：是否已登录
  const isAuthenticated = computed(() => !!user.value)

  // 计算属性：用户名
  const username = computed(() => user.value?.username || '')

  // 计算属性：用户邮箱
  const email = computed(() => user.value?.email || '')

  // 计算属性：用户头像
  const avatar = computed(() => user.value?.avatar || '')

  // 设置用户信息
  const setUser = (userData) => {
    user.value = userData
  }

  // 更新用户头像
  const updateUserAvatar = (avatarPath) => {
    if (user.value) {
      user.value = { ...user.value, avatar: avatarPath }
    }
  }

  // 清除用户信息
  const clearUser = () => {
    user.value = null
  }

  // 登出
  const logout = () => {
    authLogout()
    clearUser()
  }

  // 初始化
  initUser()

  return {
    user,
    isAuthenticated,
    username,
    email,
    avatar,
    setUser,
    updateUserAvatar,
    clearUser,
    logout,
    initUser
  }
})
